package data

import (
    "github.com/go-kratos/kratos/v2/log"
    "github.com/google/wire"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
    "gorm.io/gorm/schema"
    "mall/app/product/internal/conf"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewDB, NewProductRepo)

// Data .
type Data struct {
    db  *gorm.DB
    log *log.Helper
}

// NewData .
func NewData(db *gorm.DB, logger log.Logger) (*Data, func(), error) {
    cleanup := func() {
        log.NewHelper(logger).Info("closing the data resources")
    }
    log := log.NewHelper(log.With(logger, "module", "product-service/data"))
    data := &Data{
        db:  db,
        log: log,
    }
    return data, cleanup, nil
}

func NewDB(c *conf.Data) *gorm.DB {
    db, err := gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
        NamingStrategy: schema.NamingStrategy{
            SingularTable: true,
        },
    })
    if err != nil {
        panic(err)
    }

    if err := db.AutoMigrate(
        &Product{},
    ); err != nil {
        panic(err)
    }

    return db
}
